import re
from utils.logger import get_logger

logger = get_logger(__name__)



class RTFParser:
    @staticmethod
    def parse(rtf_data: str) -> dict:
        """解析RTF数据"""
        # 打印原始数据
        # logger.debug("RTFParser 收到的原始数据:")
        logger.debug(f"Raw data: {rtf_data}")
        # logger.debug(f"Hex representation: {' '.join(hex(ord(c))[2:] for c in rtf_data)}")
        
        result = {
            "version": None,
            "character_set": None,
            "code_page": None,
            "default_font": None,
            "font_table": [],
            "content": ""
        }
        
        # 检查语言设置
        lang_match = re.search(r'\\lang(\d+)', rtf_data)
        encoding = 'utf-8'  # 默认编码
        if lang_match and lang_match.group(1) == '2052':
            encoding = 'gbk'  # 改用 gbk 编码，它是 gb2312 的超集
            logger.debug(f"检测到中文编码设置: {encoding}")
        
        # 修改正则表达式，匹配普通文本和十六进制编码
        pard_match = re.search(r'\\pard.*?\\lang\d+\s*((?:[^\\]|(?:\\\'[0-9a-fA-F]{2})+|[a-zA-Z0-9])+).*?\\par', rtf_data, re.DOTALL)
        if pard_match:
            content = pard_match.group(1)
            logger.debug(f"提取的内容部分: {content}")
            result_text = ""
            
            i = 0
            hex_bytes = bytearray()
            
            while i < len(content):
                if content[i:i+2] == r"\'":
                    # 收集十六进制编码
                    hex_str = content[i+2:i+4]
                    hex_bytes.extend(bytes.fromhex(hex_str))
                    i += 4
                    
                    # 如果收集到足够的字节，就立即解码
                    if len(hex_bytes) >= 2:
                        try:
                            char = hex_bytes.decode(encoding, errors='replace')
                            logger.debug(f"解码字节 {hex_bytes.hex()} 为: {char}")
                            result_text += char
                            hex_bytes.clear()
                        except Exception as e:
                            logger.error(f"解码出错: {e}, hex_bytes: {hex_bytes.hex()}")
                            hex_bytes.clear()
                else:
                    # 处理普通文本
                    if content[i].isalnum() or content[i].isspace():
                        result_text += content[i]
                    i += 1
            
            # 处理最后可能剩余的十六进制编码
            if hex_bytes:
                try:
                    result_text += hex_bytes.decode(encoding, errors='replace')
                except Exception as e:
                    logger.error(f"解码最后的字节出错: {e}, hex_bytes: {hex_bytes.hex()}")
            
            result["content"] = result_text.strip()
            logger.debug(f"最终解析结果: {result['content']}")
        
        return result
